var async = require("async")
var util = require("../../../util/util.js")
var taskCfg = require("../../../conf/task.json")
var redTaskCfg = require("../../../conf/redTaskCfg.json")
module.exports = function(app) {
	return new DBRemote(app);
};

var DBRemote = function(app) {
	this.app = app
	DBRemote.app = app
    DBRemote.dbService = this.app.get("dbService")
}

var local = {}

//接取初始任务
DBRemote.prototype.gainFirstTask = function(uid,cb) {
	var taskList = {}
	for(var i in taskCfg){
		if(taskCfg[i].first){
			var tmpInfo = local.gainTask(i,0)
			if(tmpInfo){
				taskList[i] = tmpInfo
			}
		}
	}
	DBRemote.dbService.db.hmset("game:task:"+uid,taskList)
	cb()
}
//刷新每日任务
DBRemote.prototype.refreshTask = function(uid,cb){
	local.refreshTask(uid)
	cb()
}
//更新任务进度
DBRemote.prototype.updateTask = function(uid,type,value,cb){
	// console.log("updateTask")
	// console.log("uid : "+uid)
	// console.log("type : "+type)
	// console.log("value : "+value)
	local.getTaskInfo(uid,function(flag,taskList) {
		for(var i in taskList){
			taskList[i] = JSON.parse(taskList[i])
			var completedType = 0
			if(taskList[i].taskId > 8000000){
				completedType = redTaskCfg[taskList[i].taskId].completedType
			}else{
				completedType = taskCfg[taskList[i].taskId].completedType
			}
			if(completedType === type){
				local.updateTask(taskList[i],uid,value)
			}
		}
	})
	cb()
}
//获取任务信息
DBRemote.prototype.getTaskInfo = function(uid,cb){
	local.getTaskInfo(uid,function(flag,data) {
		var info = {}
		info.taskInfo = data
		DBRemote.dbService.db.hget("game:redTask:received",uid,function(err,data) {
			if(err || !data){
				info.received = 0
			}else{
				info.received = data
			}
			cb(true,info)
		})
	})
}
//领取任务奖励
DBRemote.prototype.getTaskAward = function(uid,taskId,cb){
	DBRemote.dbService.db.hget("game:task:"+uid,taskId,function(err,data) {
		if(!err && data){
			data = JSON.parse(data)
			if(data.finish && taskId < 8000000){
				local.finishTask(uid,data,cb)
			}else{
				cb(false)
			}
		}else{
			cb(false)
		}
	})
}
//领取红包任务奖励
DBRemote.prototype.getRedTaskAward = function(uid,cb) {
	local.getTaskInfo(uid,function(flag,taskList) {
		var count = 0
		for(var i in taskList){
			taskList[i] = JSON.parse(taskList[i])
			if(taskList[i].taskId > 8000000 && taskList[i].finish){
				count++
			}
		}
		if(count >= 3){
			DBRemote.dbService.db.hget("game:redTask:received",uid,function(err,data) {
				if(err || !data){
					local.getRedTaskAward(uid,cb)
				}else{
					cb(false,"已领取")
				}
			})
		}else{
			cb(false,"未完成")
		}
	})
}
//刷新红包任务
DBRemote.prototype.refreshRedTask = function(uid,cb) {
	async.waterfall([
			function(next) {
				DBRemote.dbService.db.hget("game:redTask:received",uid,function(err,data) {
					if(err || !data){
						next()
					}else{
						cb(false,"已领取")
					}
				})
			},
			function(next) {
				DBRemote.dbService.getPlayer(uid,"diamond",function(data) {
					if(!data || data < 10){
						cb(false)
						return
					}else{
						next()
					}
				})
			},
			function(next) {
				DBRemote.dbService.addItemReason(uid,101,-10,"刷新红包任务",function(flag) {
					if(flag){
						next()
					}else{
						cb(false)
					}
				})
			},
			function() {
				local.refreshRedTask(uid,cb)
			}
		],function(err) {
		console.log(err)
	})
}
//更新任务进度
local.updateTask = function(task,uid,value) {
	// console.log("updateTask",task,value)
	var completedValue = 0
	var completedType = 0
	if(task.taskId > 8000000){
		completedValue = task.completedValue
		completedType = redTaskCfg[task.taskId].completedType
	}else{
		completedValue = taskCfg[task.taskId].completedValue
		completedType = taskCfg[task.taskId].completedType
	}
	switch(completedType){
		case "goldplay":
			//金币场参玩次数
			if(task.finish == false){
				task.curValue++
				local.taskChange(uid,task.taskId,task.curValue)
			}
		break
		case "goldwin":
			//金币场胜利次数
			if(task.finish == false){
				task.curValue++
				local.taskChange(uid,task.taskId,task.curValue)
			}
		break
		case "goldstreak":
			//金币场连胜次数
			if(value > task.curValue){
				task.curValue = value
				local.taskChange(uid,task.taskId,task.curValue)
			}else{
				return
			}
		break
		case "checkpointPass":
			//通过指定关卡
			if(value >= task.curValue){
				task.curValue = value
				local.taskChange(uid,task.taskId,task.curValue)
			}else{
				return
			}
		break
		case "recharge":
			//充值
			if(value >= task.curValue){
				task.curValue = value
				local.taskChange(uid,task.taskId,task.curValue)
			}else{
				return
			}
		break
		default:
			return
	}
	if(task.finish == false && task.curValue >= completedValue){
		task.finish = true
		local.finishMessage(uid,task.taskId)
	}
	DBRemote.dbService.db.hset("game:task:"+uid,task.taskId,JSON.stringify(task))
}
//通知任务目标达成
local.finishMessage = function(uid,taskId) {
	var notify = {
		cmd : "taskFinish",
		taskId : taskId
	}
	DBRemote.app.rpc.game.remote.sendByUid(null,uid,notify,function(){})
}
//刷新每日任务
local.refreshTask = function(uid) {
	// console.log("refreshTask : "+uid)
	local.getTaskInfo(uid,function(flag,taskList) {
		var deleteList = {}
		for(var i in taskList){
			var tmpTask = JSON.parse(taskList[i])
			if(tmpTask){
				if(tmpTask.taskId > 8000000 || taskCfg[tmpTask.taskId].refresh){
					delete taskList[i]
					deleteList[i] = true
				}
			}
		}
		for(var i in taskCfg){
			if(taskCfg[i].receive){
				taskList[i] = local.gainTask(i,0)
				delete deleteList[i]
			}
		}
		//重新领取红包任务
		var arr = []
		for(var i in redTaskCfg){
			if(i != "8001001"){
				arr.push(i)
			}else{
				//领取分享任务
				taskList[i] = local.gainRedTask(i)
				delete deleteList[i]
			}
		}
		arr.sort(function(){ return 0.5 - Math.random() })
		for(var i = 0;i < 2;i++){
			taskList[arr[i]] = local.gainRedTask(arr[i])
			delete deleteList[arr[i]]
		}
		for(var i in deleteList){
			DBRemote.dbService.db.hdel("game:task:"+uid,i)
		}
		DBRemote.dbService.db.hmset("game:task:"+uid,taskList)
		local.taskChange(uid,0,0)
	})
}
//刷新红包任务
local.refreshRedTask = function(uid,cb) {
	local.getTaskInfo(uid,function(flag,taskList) {
		var deleteList = {}
		for(var i in taskList){
			var tmpTask = JSON.parse(taskList[i])
			if(tmpTask){
				if(tmpTask.taskId > 8000000){
					delete taskList[i]
					deleteList[i] = true
				}
			}
		}
		//重新领取红包任务
		var arr = []
		for(var i in redTaskCfg){
			if(!deleteList[i]){
				arr.push(i)
			}
		}
		arr.sort(function(){ return 0.5 - Math.random() })
		var tmpTaskList = {}
		for(var i = 0;i < 3;i++){
			tmpTaskList[arr[i]] = local.gainRedTask(arr[i])
			delete deleteList[arr[i]]
		}
		for(var i in deleteList){
			DBRemote.dbService.db.hdel("game:task:"+uid,i)
		}
		DBRemote.dbService.db.hmset("game:task:"+uid,tmpTaskList)
		cb(true,tmpTaskList)
	})
}
//获取任务信息
local.getTaskInfo = function(uid,cb) {
	DBRemote.dbService.db.hgetall("game:task:"+uid,function(err,data) {
		if(err || !data){
			cb(true,{})
		}else{
			cb(true,data)
		}
	})
}
//任务初始化
local.gainTask = function(taskId,curValue){
	if(!taskId || !taskCfg[taskId]){
		return false
	}
	var taskInfo = util.deepCopy(taskCfg[taskId])
	var info = {
		taskId : taskInfo.taskId,
		curValue : 0,
		finish : false
	}
	switch(taskInfo.completedType){
		case "time":
		case "cardType-1":
		case "cardType-2":
		case "cardType-3":
		case "cardType-4":
		case "cardType-5":
		case "cardType-6":
		case "cardType-7":
		case "cardType-8":
		case "cardType-9":
		case "cardType-10":
		case "cardType-11":
		case "RepelAllBlades":
		case "share":
		case "friend":
			info.finish = true
		break
		case "goldstreak":
		case "checkpointPass":
			info.curValue = curValue
			if(info.curValue && info.curValue >= taskInfo.completedValue){
				info.finish = true
			}
		break
	}
	return JSON.stringify(info)
}
//红包任务初始化
local.gainRedTask = function(taskId){
	if(!taskId || !redTaskCfg[taskId]){
		return false
	}
	var taskInfo = util.deepCopy(redTaskCfg[taskId])
	var info = {
		taskId : taskId,
		curValue : 0,
		completedValue : Math.floor(Math.random() * (taskInfo.completedMaxValue - taskInfo.completedMinValue) + taskInfo.completedMinValue),
		finish : false
	}
	switch(taskInfo.completedType){
		case "time":
		case "cardType-1":
		case "cardType-2":
		case "cardType-3":
		case "cardType-4":
		case "cardType-5":
		case "cardType-6":
		case "cardType-7":
		case "cardType-8":
		case "cardType-9":
		case "cardType-10":
		case "cardType-11":
		case "RepelAllBlades":
		case "share":
		case "friend":
			info.finish = true
		break
	}
	return JSON.stringify(info)
}
//任务完成
local.finishTask = function(uid,task,cb){
	//删除任务
	DBRemote.dbService.db.hdel("game:task:"+uid,task.taskId)
	//领取后续任务
	var laterTask = local.gainTask(taskCfg[task.taskId].laterId,task.curValue)
	if(laterTask){
		DBRemote.dbService.db.hset("game:task:"+uid,taskCfg[task.taskId].laterId,laterTask)
	}
	var awardList = {}
	//获取奖励
	if(taskCfg[task.taskId].award){
		var tmpList = taskCfg[task.taskId].award.split("&")
		for(var i = 0;i < tmpList.length;i++){
			var tmpAward = tmpList[i].split(":")
			awardList[tmpAward[0]] = parseInt(tmpAward[1])
		}
		for(var i in awardList){
			DBRemote.dbService.addItemReason(uid,parseInt(i),awardList[i],"任务",function(){})
		}
	}
	var info = {
		awardList : awardList,
		laterId : taskCfg[task.taskId].laterId,
		laterTask : laterTask
	}
	cb(true,info)
}
//任务改动
local.taskChange = function(uid,taskId,curValue) {
	var notify = {
		cmd : "taskChange",
		taskId : taskId,
		curValue : curValue
	}
	DBRemote.app.rpc.game.remote.sendByUid(null,uid,notify,function(){})
}
//获取任务红包奖励
local.getRedTaskAward = function(uid,cb) {
	DBRemote.dbService.db.hgetall("game:redTask:awardInfo",function(err,data) {
		var min = 0.1
		var max = 0.5
		var itemId = 102
		if(!err && data){
			if(data.min && data.max && data.itemId){
				min = parseFloat(data.min)
				max = parseFloat(data.max)
				itemId = data.itemId
			}
		}
		var value = Math.random() * (max - min) + min
		value = parseFloat(value.toFixed(2))
		itemId = parseInt(itemId)
		DBRemote.dbService.db.hset("game:redTask:received",uid,value)
		DBRemote.dbService.addItemReason(uid,itemId,value,"任务红包",function(){})
		cb(true,{itemId : itemId,value : value})
	})
}
